const router = require('koa-router')()
const jsonwebtoken = require('jsonwebtoken')
const { exec } = require('../db/index')
const { secret } = require('../config')
const { getPassword } = require('../utils/crypto')

// 路由前缀
router.prefix('/api/users')

// 登陆校验的中间件
const auth = async (ctx, next) => {
  const { token = '' } = ctx.request.header
  try {
    // 验证： 只要能验证出来账号密码，就说明成功了
    const user = jsonwebtoken.verify(token, secret)
    ctx.state.user = user;
  } catch(err) {
    ctx.throw(401, err.message)
  }
  await next()
}

// 注册
router.post('/register', async(ctx, next) => {
  ctx.verifyParams({
    username: { type: 'string', require: true },
    password: { type: 'string', require: true },
    realname: { type: 'string', require: true },
  })
  const regList = ctx.request.body;
  const sql = `insert into users (username, password, realname) values ('${regList.username}', '${getPassword(regList.password)}', '${regList.realname}');`
  const data = await exec(sql)
  ctx.body = data.insertId;
})

// 登陆
router.post('/login', async(ctx, next) => {
  ctx.verifyParams({
    username: { type: 'string', require: true },
    password: { type: 'string', require: true }
  })
  const loginData = ctx.request.body;
  const sql = `select * from users where username='${loginData.username}' and password='${getPassword(loginData.password)}';`
  const data = await exec(sql)
  const { id, username, password } = data[0]
  const token = jsonwebtoken.sign({id, username, password}, secret, {expiresIn:"1h"}) 
  ctx.body = {token};
})

// 给列表添加数据的接口:这个接口。必须要求用户登陆才可以使用
router.post('/list', auth, async(ctx, next) => {
  ctx.verifyParams({
    title: { type: 'string', require: true },
    content: { type: 'string', require: true },
    author: { type: 'string', require: true }
  })
  const { title, content,author } = ctx.request.body;
  const sql = `insert into bosslist (title, content, createtime, author) values ('${title}','${content}','${Date.now()}', '${author}');` 
  const data = await exec(sql)
  ctx.body = data;
})

// 一般来说什么接口需要登陆校验 （增加数据接口， 删除）
router.get('/search', async(ctx, next) => {
  ctx.verifyParams({
    keyword: { type: 'string', require: true },
  })
  const { keyword } = ctx.query;
  const sql = `select * from bosslist where title like '%${keyword}%';`
  const data = await exec(sql)
  ctx.body = data
})

// 列表查询接口
router.get('/list', async(ctx, next) => {
  const sql = `select * from bosslist order by id desc;`
  const data = await exec(sql)
  ctx.body = data;
})

module.exports = router
